package com.dongpu.springboot.rabbitmq.rabbit.simple;

import com.dongpu.springboot.rabbitmq.utils.ConnectionUtil;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author biyuyang
 */
public class MsgReceive {

	private final static String QUEUE_NAME = "q_test_01";

	public static void main(String[] argv) throws Exception {

		// 获取到连接以及mq通道
		Connection connection = ConnectionUtil.getConnection();
		// 从连接中创建通道
		Channel channel = connection.createChannel();
		// 声明队列
		channel.queueDeclare(QUEUE_NAME, false, false, false, null);

		final Consumer consumer = new DefaultConsumer(channel){
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
				byte[] body) throws IOException {
				SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSSS");

				String message = new String(body, StandardCharsets.UTF_8);

				System.out.println(" ConfirmReceiver1  : " + message);
				System.out.println(" ConfirmReceiver1 Done! at " + time.format(new Date()));
			}
		};
		// 监听队列
		channel.basicConsume(QUEUE_NAME, true, consumer);
	}
}
